package com.itheima.reggie.common;


import com.itheima.reggie.entity.OperationLog;
import com.itheima.reggie.service.OperationLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
public class OperationAspect {

    @Autowired
    private OperationLogService op;

    //1.切入点表达式，标识那些是切入点(需要增强的方法)
    @Pointcut("@annotation(com.itheima.reggie.common.Log)")
    private void operationMethod() {
    }


    //2.如何对那些方法进行那些增强

    //3.通知具体的增强代码
    @Around("operationMethod()")
    public Object operationLogHandle(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Log annotation = method.getAnnotation(Log.class);
        String value = annotation.value();




        OperationLog operationLog = new OperationLog();
        operationLog.setUserId(BaseContext.getCurrentId());
        operationLog.setUpdateTime(LocalDateTime.now());



        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
            Thread t = new Thread(new Runnable(){
                public void run(){
                    operationLog.setText("用户在执行："+value+"出错");
                    op.save(operationLog);
                }});
            t.start();
        } finally {
            Thread t = new Thread(new Runnable(){
                public void run(){
                    operationLog.setText(value);
                    op.save(operationLog);
                }});
            t.start();
        }
        return proceed;
    }
}
